//数据绑定插件
(function($){
    //格式化字符串
    $.tmpl = function(t, d){
        return t.replace( /\$\{([^\}]*)\}/g, function(m,c){return d[c]||"";});
    }
    //ajax数据源
    $.dataprovider = function(url, spliter){
        var self = this;
        self.callback = function(){};
        self.url = url;
        self.obj = null;
        this.getData = function(){
            var data = $.getCacheData(self.url);
            if(data){
                if(spliter != null)
                    data = spliter.call(this, data);
                self.callback.call(self, self.obj, data);
                return;
            }
            $.mobile.showPageLoadingMsg('', '数据载入中...');
            $.get(self.url, function(data){
                $.cacheData(self.url, data)
                if(spliter != null)
                    data = spliter.call(this, data);
                self.callback.call(self, self.obj, data);
            },'json')
            .error(function(){$.mobile.showMessage('数据载入出错')})
            .complete(function() { $.mobile.hidePageLoadingMsg(); })
        }
    };
    //缓存数据
    $.cacheData = function(key, data){
//        $.cacheDataValue[key] = data;
        localStorage[key] = JSON.stringify(data)
    }
    //获取缓存数据
    $.getCacheData = function(key){
//        if($.cacheDataValue == null) {
//            $.cacheDataValue = {};
//            return false;
//        }
//        return $.cacheDataValue[key] == null ? false : $.cacheDataValue[key];
        var stor = localStorage[key];
        if(stor)
            return JSON.parse(stor);
        return false;
    }
    
    //判断是否需要缓存页面
    $.cachePage = function(to, from){
        if($(to).attr("data-dom-cache") != "true") return false;
        if(!$(to).data('pagecreated')){
            $(to).data('pagecreated', true);
            return false;
        }
        if($(from).attr('id') == 'home') return false;
        return true;
    }
    
    //列表适配器，可以把数据与列表项组装起来
    $.listadapter = function(parm){
        var self = this;
        self.template = "<li><a href=''>${courseName}</a></li>";
        this.callback = function(obj, data){
            var html = '';
            for(var i in data){
                html += $.tmpl(self.template, data[i])
            }
            $(obj).html(html).listview('refresh', true).attr('scrollTop', 0);
        };
        if(typeof(parm) == 'string'){
            this.template = parm;
        }else if(typeof(parm) == 'function'){
            this.callback = parm;
        }
    }

    $.fn.databind = function(opt,callback) {
        var self = this;
        if(!opt) return false;
        self.find('[data-bind]').each(function(index, obj){
            var colunm = $(obj).attr('data-bind');
            if(opt[colunm] == null) return true;
            $(obj).html(opt[colunm]);
        })
    };
    
    //把列表与数据源绑定，数据源更新则列表也更新
    $.fn.bindlist = function(adapter, dataprovider){
        var self = this;
        dataprovider.obj = self;
        dataprovider.callback = adapter.callback;
        dataprovider.getData();
    };
})(jQuery);
//数据绑定插件 end

//记录返回路径
var page_level = 0;
var page_history = ['./'];

function keep_state(level){
    page_history[level] = window.location.href;
}

function goto_state(level){
    var url = page_history[level] == null ? page_history[0] : page_history[level];
    $.mobile.changePage(url, {'reverse':true});
}
//记录返回路径end

function getQueryString(name){
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
//添加cookie
function setCookie(c_name, value)
{
    var expiredays = 30;
    var exdate = new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    var cookieVal=c_name+ "=" +escape(value)+((expiredays == null) ? "" : ";expires="+exdate.toGMTString());
    document.cookie=cookieVal;
}
//获取cookie
function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        var c_start = document.cookie.indexOf(c_name + "=")
        if (c_start!=-1)
        { 
            c_start=c_start + c_name.length+1 
            var c_end = document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        } 
    }
    return ""
}
var ismenushow = false;
function togglemenu(){
    $('.ui-page-active').off('mousedown')
    if(ismenushow){
        hidemenu()
    }else{
        $('.ui-page-active').addClass('menu_onshow_page')
        $('.ui-header,.ui-footer').addClass('menu_onshow_fixed')
        $('#main_menu').show()
        ismenushow = true
    }
    setTimeout(function(){
        $('.ui-page-active').mousedown(function(){hidemenu()})
    }, 1)
}
function gomenu(href){
    hidemenu()
    $.mobile.changePage(href);
}
function hidemenu(){
    $('#main_menu').hide();
    $('.ui-page-active').removeClass('menu_onshow_page').off('mousedown')
    $('.ui-header').removeClass('menu_onshow_fixed')
    ismenushow = false
}

//临时函数
var student = {
    login : function(){
        if(this.getLoginName() == ''){
            window.location = '?p=login';
        }
    },
    getLoginName : function(){
        return getCookie('LoginName');
    },
    getLcenterId : function(){
        return getCookie('LcenterId');
    }
}
student.login();


//jqm初始化参数
$(document).bind("mobileinit", function(){
    $.mobile.defaultPageTransition = 'slide'
    $.mobile.loadingMessageTextVisible = true;
    $.mobile.loadingMessage = '页面载入中...';
    $.mobile.showMessage = function(text){
        setTimeout( function(){$.mobile.showPageLoadingMsg('e', text, true);}, 100 );
        setTimeout( $.mobile.hidePageLoadingMsg, 3000 );
    }
    if(!$.mobile.gradeA()) alert('您的浏览器可能无法访问全部功能')
});
//jqm初始化参数 end


//个人信息页面
$('#profile').live('pageshow', function(e, data){
    keep_state(1);
    var loginName = student.getLoginName();
    var self = $(this);
    $.mobile.showPageLoadingMsg('', '数据载入中...');
    $.get('data.php?a=studentinfo&loginName='+loginName,function(data){
        self.databind(data.studentInfo);
    },'json').complete(function() { $.mobile.hidePageLoadingMsg(); });
})


//费用信息
$('#profile_feiyong').live('pageshow', function(e, data){
    keep_state(1);
    var loginName = student.getLoginName();
    var self = $(this);
    $.mobile.showPageLoadingMsg('', '数据载入中...');
    $.get('data.php?a=fareinfo&loginName='+loginName,function(data){
        self.databind(data.fareInfo);
    },'json').complete(function() { $.mobile.hidePageLoadingMsg(); });
})

//学习中心信息
$('#profile_lcenter').live('pageshow', function(e, data){
    keep_state(1);
    var lcenterid = student.getLcenterId();
    var self = $(this);
    $.mobile.showPageLoadingMsg('', '数据载入中...');
    $.get('data.php?a=lcenter&id='+lcenterid,function(data){
        if(!data) return;
        var tels = data['tel'].split(' ');
        if(tels[0]){
            for(var i in tels){
                if(tels[i] == '') tels.splice(i,1);
                tels[i] = tels[i].replace(/(^\s*)|(\s*$)/g, "")
            }
            $('.lcenter_tel').attr('href', 'tel:'+tels[0]);
            data['tel'] = tels.join('<br>')
        }
        self.databind(data);
    },'json').complete(function() { $.mobile.hidePageLoadingMsg(); });
})

//考场信息
$('#kaochang').live('pageshow', function(e, data){
    keep_state(1);
    var loginName = student.getLoginName();
    var adp = new $.listadapter(function(obj, data){
        if(!data || data.length == 0) {
            $.mobile.showMessage("暂时没有考场信息");
            return false;
        }
        obj.find('.table1').databind(data[0])
        var tpl = '<table border="0" cellspacing="0" width="100%"><caption>${number}</caption>\n\
                    <tbody><tr><td width="30%" align="right">考试时间：</td><td>${examTime}</td></tr>\n\
                    <tr><td align="right">考场：</td><td>${examRoom}</td></tr><tr><td align="right">考场地址：</td><td>${locationAddress}</td></tr>\n\
                    <tr><td align="right">考试科目：</td><td>${course}</td></tr><tr><td align="right">卷别：</td><td>${paperType}</td></tr>\n\
                    <tr><td align="right">座位号：</td><td>${seatNumber}</td></tr></tbody></table><br/>'
        var html = '';
        for(var i in data){
            html += $.tmpl(tpl, data[i]);
        }
        obj.find('.table2').html(html);
    })
    var pdv = new $.dataprovider('data.php?a=EXAMROOM&loginname='+loginName, function(data){return data['examRoom']})
    $(this).bindlist(adp, pdv);
})

//成绩信息总部
$('#chengji').live('pageshow', function(e, data){
    keep_state(1);
    var loginName = student.getLoginName();
    var self = $(this);
    var id = self.attr('id')
    var adp = new $.listadapter(function(obj, data){
        var tpl1 = '<tr><td>${checkWay}</td><td>${proportion}%</td><td>${score}</td><td>${extraScore}</td></tr>';
        var tpl2 = '<tr><td rowspan="${recordsnum}">${courseName}</td><td>${checkWay}</td><td>${proportion}%</td>\n\
<td>${score}</td><td>${extraScore}</td><td rowspan="${recordsnum}">${totalScore}</td></tr>';
        var html = '';
        for(var i in data){
            for(var j in data[i]['records']){
                var row = {
                    'courseName':data[i]['courseName'],
                    'totalScore':data[i]['totalScore']+'',
                    'recordsnum':data[i]['records'].length,
                    'checkWay'  :data[i]['records'][j]['checkWay'],
                    'proportion'  :data[i]['records'][j]['proportion'],
                    'score'  :data[i]['records'][j]['score']+'',
                    'extraScore'  :data[i]['records'][j]['extraScore']+''
                }
                var tpl = j == 0 ? tpl2 : tpl1;
                html += $.tmpl(tpl, row);
            }
        }
        obj.html(html)
    });
    var pdv = new $.dataprovider('data.php?a=EXAMRESULT_MANAGE&loginName='+loginName, function(data){return data['examResultForManage']});
    $(this).find('tbody').bindlist(adp, pdv);
})

//成绩信息自主
$('#chengjizz').live('pageshow', function(e, data){
    keep_state(1);
    var loginName = student.getLoginName();
    var self = $(this);
    var id = self.attr('id')
    var adp = new $.listadapter(function(obj, data){
        var tpl1 = '<tr><td>${examInfo}</td><td>${percentum}%</td><td>${examScore}</td></tr>';
        var tpl2 = '<tr><td rowspan="${recordsnum}">${courseName}</td><td>${examInfo}</td><td>${percentum}%</td>\n\
<td>${examScore}</td><td rowspan="${recordsnum}">${annexScore}</td><td rowspan="${recordsnum}">${courseScore}</td></tr>';
        var html = '';
        for(var i in data){
            for(var j in data[i]['examModes']){
                var row = {
                    'courseName':data[i]['courseName'],
                    'courseScore':data[i]['courseScore']+'',
                    'annexScore':data[i]['annexScore']+'',
                    'recordsnum':data[i]['examModes'].length,
                    'examInfo'  :data[i]['examModes'][j]['examInfo'],
                    'percentum'  :data[i]['examModes'][j]['percentum'],
                    'examScore'  :data[i]['examModes'][j]['examScore']+''
                }
                var tpl = j == 0 ? tpl2 : tpl1;
                html += $.tmpl(tpl, row);
            }
        }
        obj.html(html)
    });
    var pdv = new $.dataprovider('data.php?a=EXAMRESULT_PERSON&loginName='+loginName, function(data){return data['examResultForPerson']});
    $(this).find('tbody').bindlist(adp, pdv);
})

//作业课程列表
$('#zuoye').live('pageshow', function(e, data){
    keep_state(1);
    if($.cachePage(e.target, data.prevPage))  return true;
    var loginName = student.getLoginName();
    
    var tmp = '<div data-role="collapsible" data-inset="false"><h3>${courseName}<span style="float:right">${courseScore}</span></h3>${workhtml}</div>';
    var worktmp = "<tr><td>${WORKER_NAME}</td><td>${DO_COUNT}</td><td>${WORKER_SCORE}</td><td><a href='?p=zuoye_questions&tactic_id=${WORKER_ID}&coursecd=${courseID}'>进入</a></td></tr>"
    var adp = new $.listadapter(function(obj, data){
        obj.html('')
        for(var i in data){
            var workhtml = '<table width="100%"><thead><tr><th>试卷名称</th><th>次数</th><th>得分</th><th>作业操作</th></tr></thead><tbody>';
            for(var w in data[i]['worklist']){
                data[i]['worklist'][w]['courseID'] = data[i]['courseID'];
                workhtml += $.tmpl(worktmp, data[i]['worklist'][w]);
            }
            workhtml += "</tbody></table>";
            data[i]['workhtml'] = workhtml;
            data[i]['courseScore'] = new Number(data[i]['courseScore']).toFixed(2);
            var html = $.tmpl(tmp, data[i]);
            $(html).collapsible().appendTo(obj)
        }
    })
    var pdv = new $.dataprovider('data.php?a=HOMEWORKCOURSE&loginName='+loginName, function(data){return data['homeworkCourselist']});
    $(this).find('.collapsible-content').bindlist(adp, pdv);
    $(e.target).data('pagecreated', true);
})

$('#zuoye_questions').live('pageshow',function(e, data){
    keep_state(2);
    var loginName = student.getLoginName();
    var parms = {'TACTICID':getQueryString('tactic_id'),'COURSECD':getQueryString('coursecd'),'UID':loginName};
    var url = 'data.php?a=TK_QUESTIONS&t='+parms['TACTICID']+'&u='+loginName;
    var pr = new paper(url, $(this).find('div[data-role=content]'), parms);
    pr.canSubmit = true;
    
    pr.setPrevBtn($(this).find('div[data-role=footer] a.prev_btn'))
    pr.setNextBtn($(this).find('div[data-role=footer] a.next_btn'))
    pr.setAnswerBtn($(this).find('div[data-role=footer] a.submit_btn'))
    pr.setFavBtn($(this).find('a.favbtn'))
})

//成绩合成
$('#cjhc').live('pageshow', function(e, data){
    keep_state(1);
    var loginName = student.getLoginName();
    var self = this;
    var urlcompose = 'data.php?a=SCORECOMPOSE&loginname='+loginName
    
    var tmp = '<div data-role="collapsible" data-inset="false"><h3>${courseName}<span style="float:right">${courseScore}</span></h3>${workhtml}</div>';
    var worktmp = "<tr><td>${WORKER_NAME}</td><td>${DO_COUNT}</td><td>${WORKER_SCORE}</td></tr>"
    var adp = new $.listadapter(function(obj, data){
        obj.html('')
        for(var i in data){
            var workhtml = '<table width="100%"><thead><tr><th>试卷名称</th><th>次数</th><th>得分</th></tr></thead><tbody>';
            for(var w in data[i]['worklist']){
                data[i]['worklist'][w]['courseID'] = data[i]['courseID'];
                workhtml += $.tmpl(worktmp, data[i]['worklist'][w]);
            }
            workhtml += "<tr><td colspan='4'><a href='#' data-role='button' data-courseid='"+data[i]['courseID']+"'>成绩合成</a></td></tr>";
            workhtml += "</tbody></table>";
            data[i]['workhtml'] = workhtml;
            var html = $.tmpl(tmp, data[i]);
            $(html).collapsible().appendTo(obj)
        }
        $(self).find('[data-courseid]').click(function(){
            var courseid = $(this).attr('data-courseid');
            $.mobile.showPageLoadingMsg('', '正在合成成绩...');
            $.get(urlcompose+'&courseid='+courseid, function(result){
                alert(result.message)
            },'json')
            .error(function(){alert('成绩合成出错')})
            .complete(function(){$.mobile.hidePageLoadingMsg();})
        })
    })
    var pdv = new $.dataprovider('data.php?a=COMPOSECOURSE&loginName='+loginName, function(data){return data['scoreCompose']});
    $(this).find('.collapsible-content').bindlist(adp, pdv);
})

//随堂随练课程列表
$('#stsl').live('pageshow', function(e, data){
    keep_state(1);
    if($.cachePage(e.target, data.prevPage))  return true;
    var loginName = student.getLoginName();
    
    var adp = new $.listadapter('<li><a href="?p=stsl_chapters&courseValue=${courseID}">${courseName}</a></li>');
    var pdv = new $.dataprovider('data.php?a=HORVERSTEHENCOURSE&loginName='+loginName, function(data){return data['horverstehenCourselist']});
    $(this).find('[data-role=listview]').bindlist(adp, pdv);
})

//随堂随练章节列表
$('#stsl_chapters').live('pageshow', function(e, data){
    keep_state(2);
    if($.cachePage(e.target, data.prevPage))  return true;
    var loginName = student.getLoginName();
    var courseValue = getQueryString('courseValue');
    
    var tmp = '<div data-role="collapsible" data-inset="false"><h3>${CHAPTER_NAME}<span style="float:right">${EXER_SCORE} 分</span></h3>${workhtml}</div>';
    var tmp2 = '<a href="?p=stsl_questions&tactic_id=${tactic_id}&chapter_id=${CHAPTER_ID}&uid='+loginName+'&coursecd='+courseValue+'" data-role="button" data-corners="false"><span style="float:left">${CHAPTER_NAME}</span> <span style="float:right">${EXER_SCORE} 分</span></a>';
    var worktmp = "<li><a href='?p=stsl_questions&tactic_id=${tactic_id}&chapter_id=${CHAPTER_ID}&uid="+loginName+"&coursecd="+courseValue+"'>${CHAPTER_NAME}</a></li>"
    var adp = new $.listadapter(function(obj, data){
        obj.html('')
        for(var i in data){
            data[i]['EXER_SCORE'] = ''+data[i]['EXER_SCORE'];
            if(data[i]['buttonFlag'] == '0'){
                if(!data[i]['chapters'] || data[i]['chapters'].length==0){
                    var workhtml ="<span>当前章下没有小节</span>";
                }else{
                    var workhtml = '<ul data-role="listview" data-theme="a">';
                    for(var w in data[i]['chapters']){
                        workhtml += $.tmpl(worktmp, data[i]['chapters'][w]);
                    }
                    workhtml += "</ul>";
                }
                data[i]['workhtml'] = workhtml;
                var html = $.tmpl(tmp, data[i]);
                $(html).collapsible().appendTo(obj)
            }else{
                var html = $.tmpl(tmp2, data[i]);
                $(html).appendTo(obj)
            }
        }
        $.mobile.pageContainer.trigger('create');
    })
    
    var pdv = new $.dataprovider('data.php?a=STSL_TREETOP&courseValue='+courseValue+'&loginName='+loginName);
    $(this).find('.collapsible-content').bindlist(adp, pdv);
})

//随堂随练试卷
$('#stsl_questions').live('pageshow',function(e, data){
    keep_state(3);
    var loginName = student.getLoginName();
    var chapter_id = getQueryString('chapter_id');
    var parms = {'TACTICID':getQueryString('tactic_id'),'COURSECD':getQueryString('coursecd'),'UID':loginName};
    var url = 'data.php?a=STSL_QUESTIONS&t='+parms['TACTICID']+'&c='+chapter_id+'&u='+loginName;
    var pr = new paper(url, $(this).find('div[data-role=content]'), parms);
    
    pr.setPrevBtn($(this).find('div[data-role=footer] a.prev_btn'))
    pr.setNextBtn($(this).find('div[data-role=footer] a.next_btn'))
    pr.setResultBtn($(this).find('a.result_btn'))
    pr.setAnswerBtn($(this).find('div[data-role=footer] a.submit_btn'))
})

//收藏
$('#fav').live('pageshow',function(e, data){
    var loginName = student.getLoginName();
    var chapter_id = getQueryString('chapter_id');
    var parms = {'TACTICID':getQueryString('tactic_id'),'COURSECD':getQueryString('coursecd'),'UID':loginName};
    var url = 'data.php?a=STSL_QUESTIONS&t='+parms['TACTICID']+'&c='+chapter_id+'&u='+loginName;
    var pr = new paper('', $(this).find('div[data-role=content]'));
    pr.loadFav();
    
    pr.setPrevBtn($(this).find('div[data-role=footer] a.prev_btn'))
    pr.setNextBtn($(this).find('div[data-role=footer] a.next_btn'))
    pr.setResultBtn($(this).find('a.result_btn'))
    pr.setAnswerBtn($(this).find('div[data-role=footer] a.submit_btn'))
})

//综合练习课程列表
$('#zhlx').live('pageshow', function(e, data){
    keep_state(1);
    var loginName = student.getLoginName();
    
    var tmp = '<div data-role="collapsible" data-inset="false"><h3>${courseName}<span style="float:right">${courseScore}</span></h3>${workhtml}</div>';
    var worktmp = "<tr><td>${WORKER_NAME}</td><td>${DO_COUNT}</td><td>${WORKER_SCORE}</td><td><a href='?p=zhlx_questions&tactic_id=${WORKER_ID}&coursecd=${courseID}'>进入</a></td></tr>"
    var adp = new $.listadapter(function(obj, data){
        obj.html('')
        for(var i in data){
            var workhtml = '<table width="100%"><thead><tr><th>试卷名称</th><th>次数</th><th>得分</th><th>作业操作</th></tr></thead><tbody>';
            for(var w in data[i]['worklist']){
                data[i]['worklist'][w]['courseID'] = data[i]['courseID'];
                workhtml += $.tmpl(worktmp, data[i]['worklist'][w]);
            }
            workhtml += "</tbody></table>";
            data[i]['workhtml'] = workhtml;
            var html = $.tmpl(tmp, data[i]);
            $(html).collapsible().appendTo(obj)
        }
    })
    var pdv = new $.dataprovider('data.php?a=PRACTICECOURSE&loginName='+loginName, function(data){return data['practiceCourselist']});
    $(this).find('.collapsible-content').bindlist(adp, pdv);
})

//综合练习试卷
$('#zhlx_questions').live('pageshow',function(e, data){
    keep_state(2);
    var loginName = student.getLoginName();
    var parms = {'TACTICID':getQueryString('tactic_id'),'COURSECD':getQueryString('coursecd'),'UID':loginName};
    var url = 'data.php?a=PRACTICEPAPER&t='+parms['TACTICID']+'&u='+loginName+"&topic_type=";
    var pr = new paper(url, $(this).find('div[data-role=content]'), parms);
    pr.typelist = $(this).find('.topictypes');
    
    pr.setPrevBtn($(this).find('div[data-role=footer] a.prev_btn'))
    pr.setNextBtn($(this).find('div[data-role=footer] a.next_btn'))
    pr.setResultBtn($(this).find('a.result_btn'))
    pr.typelist.change(function(){
        pr.url = url+$(this).val();
        pr.load();
    })
    pr.setAnswerBtn($(this).find('div[data-role=footer] a.submit_btn'))
})

//辅导板块列表
$('#fudao').live('pageshow', function(e, data){
    keep_state(1);
    var loginName = student.getLoginName();
    
    var adp = new $.listadapter(function(self, data){
        var listitem = '';
        for(var aid in data)
        {
            var aname = data[aid]['name'];
            listitem += '<li data-role="list-divider">'+aname+'</li>';
            for(var b in data[aid]['children'])
            {
                var itemdata = data[aid]['children'][b];
                listitem += '<li><a href="?p=fudao_topics&bid='+itemdata['id']+'">'+itemdata['name']+'</a></li>';
            }
        }
        self.html(listitem).listview('refresh', true);
    });
    var pdv = new $.dataprovider('data.php?a=FD_BOARDS&loginName='+loginName+'&parentid=');
    $(this).find('[data-role=listview]').bindlist(adp, pdv);
})

//辅导帖子列表
$('#fudao_topics').live('pageshow', function(e, data){
    keep_state(2);
    if($.cachePage(e.target, data.prevPage))  return true;
    var loginName = student.getLoginName();
    var bid = getQueryString('bid');
    var self = this, count = 0, pagesize = 20, currentpage = 1, pagenum = 0;
    
    var dataurl = 'data.php?a=FD_TOPICS&loginName='+loginName+'&boardid='+bid+"&special=false"+'&page=${page}';
    var adp = new $.listadapter('<li><a href="?p=fudao_viewtopic&tid=${tid}">${title}</a></li>');
    var pdv = new $.dataprovider($.tmpl(dataurl, {'page':currentpage}), function(data){
        count = data['count'];
        pagenum = Math.max(Math.ceil(count / pagesize), 1);
        return data['list'];
    });
    $(this).find('[data-role=listview]').eq(1).bindlist(adp, pdv);
    var changepPage = function(page){
        currentpage = page;
        pdv.url = $.tmpl(dataurl, {'page':page});
        pdv.getData();
        $(self).find('.num_btn span').text("第 "+page+" 页");
        window.scrollTo( 0, 1 );
    }
    //首页
    $(this).find('.home_btn').click(function(){
        if(currentpage == 1) return false;
        changepPage(1);
    })
    //后页
    $(this).find('.next_btn').click(function(){
        if(currentpage >= pagenum) return false;
        changepPage(currentpage+1);
    })
    //前页
    $(this).find('.prev_btn').click(function(){
        if(currentpage <= 1) return false;
        changepPage(currentpage-1);
    })
    //前页
    $(this).find('.refresh_btn').click(function(){
        changepPage(currentpage);
    })
})

//辅导精华帖子列表
$('#fudao_topics_special').live('pageshow', function(e, data){
    keep_state(2);
    var loginName = student.getLoginName();
    var bid = getQueryString('bid');
    var self = this, count = 0, pagesize = 20, currentpage = 1, pagenum = 0;
   
    var dataurl = 'data.php?a=FD_TOPICS&loginName='+loginName+'&boardid='+bid+"&special=true"+'&page=${page}';
    var adp = new $.listadapter('<li><a href="?p=fudao_viewtopic&tid=${tid}">${title}</a></li>');
    var pdv = new $.dataprovider($.tmpl(dataurl, {'page':currentpage}), function(data){
        count = data['count'];
        pagenum = Math.max(Math.ceil(count / pagesize), 1);
        return data['list'];
    });
    $(this).find('[data-role=listview]').eq(1).bindlist(adp, pdv);
    var changepPage = function(page){
        currentpage = page;
        pdv.url = $.tmpl(dataurl, {'page':page});
        pdv.getData();
        $(self).find('.num_btn span').text("第 "+page+" 页");
        window.scrollTo( 0, 1 );
    }
    //首页
    $(this).find('.home_btn').click(function(){
        if(currentpage == 1) return false;
        changepPage(1);
    })
    //后页
    $(this).find('.next_btn').click(function(){
        if(currentpage >= pagenum) return false;
        changepPage(currentpage+1);
    })
    //前页
    $(this).find('.prev_btn').click(function(){
        if(currentpage <= 1) return false;
        changepPage(currentpage-1);
    })
    //前页
    $(this).find('.refresh_btn').click(function(){
        changepPage(currentpage);
    })
})

//辅导帖子查看页面
$('#fudao_viewtopic').live('pageshow', function(e, data){
    keep_state(3);
    var loginName = student.getLoginName();
    var tid = getQueryString('tid');
    var self = this, count = 0, pagesize = 20, currentpage = 1, pagenum = 0;
    var dataurl = 'data.php?a=FD_VIEWTOPIC&loginName='+loginName+'&topicid='+tid+'&page=${page}';
    
    var adp = new $.listadapter(function(obj, list){
        var html = '';
        $(self).find('caption').html(list[0]['title'])
        for(var i in list)
        {
            var title = list[i]['title'];
            var content = list[i]['contents'];
            var author = list[i]['author'];
            var audit = list[i]['audit'] ? '审核通过' : '审核不通过';
            html += "<tr><td>"+author+"<span style='float: right'>"+audit+"</span></td></tr>";
            html += "<tr><td>"+content+"</td></tr>";
        }
        $(self).find('tbody').html(html)
    });
    var pdv = new $.dataprovider($.tmpl(dataurl, {'page':currentpage}), function(data){
        count = data['count'];
        pagenum = Math.max(Math.ceil(count / pagesize), 1);
        return data['list'];
    });
    $(this).find('[data-role=listview]').eq(1).bindlist(adp, pdv);
    var changepPage = function(page){
        currentpage = page;
        pdv.url = $.tmpl(dataurl, {'page':page});
        pdv.getData();
        $(self).find('.num_btn span').text("第 "+page+" 页");
        window.scrollTo( 0, 1 );
    }
    //首页
    $(this).find('.home_btn').click(function(){
        if(currentpage == 1) return false;
        changepPage(1);
    })
    //后页
    $(this).find('.next_btn').click(function(){
        if(currentpage >= pagenum) return false;
        changepPage(currentpage+1);
    })
    //前页
    $(this).find('.prev_btn').click(function(){
        if(currentpage <= 1) return false;
        changepPage(currentpage-1);
    })
    //前页
    $(this).find('.refresh_btn').click(function(){
        changepPage(currentpage);
    })
})

//辅导发帖页面
$('#fudao_post').live('pageshow', function(e, data){
    keep_state(3);
    var loginName = student.getLoginName();
    var self = $(this);
    var bid = getQueryString('bid');
    var postbtn = self.find('input:button').eq(0);
    
    var posturl = "data.php?a=FD_POSTTOPIC&username="+loginName+"&boardid="+bid;
    postbtn.click(function(){
        var title = self.find('input[name=title]').val();
        var content = self.find('textarea[name=content]').val();
        $.mobile.showPageLoadingMsg('', '发送中...');
        $.post(posturl, {'title':title, 'content':content},function(result){
            if(result==null || result['result'] == null) {
                $.mobile.showMessage('发生错误');
                return;
            }
            if(result['result'] == 'failed'){
                $.mobile.showMessage(result['error']);
            }else{
                $.mobile.showMessage('发送成功');
                setTimeout(function(){$.mobile.changePage('?p=fudao_viewtopic&tid='+result['topicid'])}, 2000)
            }
        },'json')
        .complete(function() { $.mobile.hidePageLoadingMsg(); })
    })
})

//辅导回帖页面
$('#fudao_reply').live('pageshow', function(e, data){
    keep_state(3);
    var loginName = student.getLoginName();
    var self = $(this);
    var tid = getQueryString('tid');
    var postbtn = self.find('input:button').eq(0);
    
    var posturl = "data.php?a=FD_POSTREPLY&username="+loginName+"&tid="+tid;
    postbtn.click(function(){
        var content = self.find('textarea[name=content]').val();
        $.mobile.showPageLoadingMsg('', '发送中...');
        $.post(posturl, {'content':content},function(result){
            if(result==null || result['result'] == null) {
                $.mobile.showMessage('发生错误');
                return;
            }
            if(result['result'] == 'failed'){
                $.mobile.showMessage(result['error']);
            }else{
                $.mobile.showMessage('发送成功');
                setTimeout(function(){$.mobile.changePage('?p=fudao_viewtopic&tid='+tid)}, 2000)
            }
        },'json')
        .complete(function() { $.mobile.hidePageLoadingMsg(); })
    })
})